﻿using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Win32;

namespace PgBirdie.Core.Service.Infrastructure
{
    public class SystemApplicationService : ISystemApplicationService
    {
        public IList<string> GetInstalledApplicationNames()
        {
            var items = new List<string>();            

            using (var key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall"))
            {
                if (key == null)
                    throw new NullReferenceException("Key was void.");
                
                foreach (var subKeyName in key.GetSubKeyNames())
                {
                    using (var subkey = key.OpenSubKey(subKeyName))
                    {
                        if (subkey == null)
                            throw new NullReferenceException("Sub key was void.");
                        var applicationName = subkey.GetValue("DisplayName");
                        if (applicationName == null)
                            continue;
                        items.Add(applicationName.ToString());
                    }
                }
            }

            return items.OrderBy(c => c).ToList();
        }
    }
}